<template>
  <div class="JNPF-common-layout">
    <div class="JNPF-common-layout-left">
      <div class="tree-search">
        <el-input placeholder="输入分类搜索" v-model="filterText" clearable></el-input>
      </div>
      <el-tree :data="treeData" :props="treeProps" highlight-current ref="treeBox" :filter-node-method="filterNode"
        :default-expanded-keys="[-1]" :default-checked-keys="[-1]" @node-click="handleNodeClick" class="JNPF-common-el-tree" node-key="id">
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <i :class="data.icon"></i>
          <span class="text">{{node.label}}</span>
        </span>
      </el-tree>
    </div>
    <div class="JNPF-common-layout-center">
      <el-row class="JNPF-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="">
              <el-input v-model="query.keyWord" placeholder="输入商品编号、名称" clearable> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-select v-model="query.showMark" placeholder="选择商品状态" clearable>
                <el-option v-for="(item, index) in showmarkOptions" :key="index" :label="item.fullName" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker v-model="query.creatorTime" value-format="timestamp" format="yyyy-MM-dd"
                start-placeholder="发布开始日期" end-placeholder="发布结束日期" type="daterange" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset(true)">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JNPF-common-layout-main JNPF-flex-main">
        <div class="JNPF-common-head">
          <div>
            <el-button v-has="'btn_add'" type="primary" icon="el-icon-plus" @click="addOrUpdateHandle()">新增</el-button>
            <!-- <el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button> -->
          </div>
          <div class="JNPF-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link icon="icon-ym icon-ym-Refresh JNPF-common-head-icon" :underline="false" @click="reset(true)" />
            </el-tooltip>
          </div>
        </div>
        <JNPF-table v-loading="listLoading" :data="list" @sort-change='sortChange' :span-method="arraySpanMethod">
          <el-table-column prop="goodsCode" label="商品编号" align="left" width="130" />
          <el-table-column prop="name" label="商品名称" align="left" show-overflow-tooltip />
          <el-table-column prop="image" label="商品图片" align="left">
            <template slot-scope="scope">
              <el-image v-if="scope.row.url" :src="define.comUrl+scope.row.url" class="el-upload-list__item-thumbnail"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="所属分类" prop="goodsTypeName" algin="left">
            <template slot-scope="scope">
              {{ scope.row.goodsTypeName || '商品分类' }}
            </template>
          </el-table-column>
          <el-table-column prop="flowState" label="审核状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.flowState==1">待审核</el-tag>
              <el-tag type="success" v-else-if="scope.row.flowState==2">已审核</el-tag>
              <el-tag type="danger" v-else-if="scope.row.flowState==3">已驳回</el-tag>
              <!-- <el-tag type="info" v-else-if="scope.row.flowState==4">流程撤回</el-tag> -->
              <!-- <el-tag type="info" v-else-if="scope.row.flowState==5">审核终止</el-tag> -->
              <el-tag type="warning" v-else>保存</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="商品状态" prop="showMark" algin="left">
            <template slot-scope="scope">
              {{ scope.row.showMark ==1 ? '上架' : '下架'}}
            </template>
          </el-table-column>
          <el-table-column prop="creatorTime" label="发布时间" align="left" format="yyyy-MM-dd" width="140" accesskey=""/>
          <el-table-column label="操作" fixed="right" width="100">
            <template slot-scope="scope">
              <el-button v-has="'btn_up'" type="text" v-if="[3, 0].indexOf(scope.row.flowState)>-1" @click="showHandle(scope.row.id)">上架</el-button>
              <el-button v-has="'btn_down'" type="text" v-if="[2].indexOf(scope.row.flowState)>-1" @click="offHandle(scope.row.id)">下架</el-button>
              <el-button v-has="'btn_edit'" type="text" v-if="[3, 0].indexOf(scope.row.flowState)>-1" @click="addOrUpdateHandle(scope.row.id)">编辑</el-button>
              <el-button v-has="'btn_detail'" type="text" v-if="[1, 2].indexOf(scope.row.flowState)>-1" @click="addOrUpdateHandle(scope.row.id,scope.row.flowState)">详情</el-button>
              <el-button v-has="'btn_remove'" type="text" class="JNPF-table-delBtn" @click="handleDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </JNPF-table>
        <pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
          @pagination="initData" />
      </div>
    </div>
    <FlowBox v-if="flowVisible" ref="FlowBox" @close="colseFlow" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" :displayReturn="false" />
  </div>
</template>
<script>
  import request from '@/utils/request'
  import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
  import FlowBox from '@/views/workFlow/components/FlowBox'
  import ExportBox from './ExportBox'
  import { getDataInterfaceRes } from '@/api/vip/goodsList'
  import columnList from './columnList'
  export default {
    components: {
      FlowBox,
      ExportBox
    },
    data() {
      return {
        expandObj: {},
        columnOptions: [],
        mergeList: [],
        exportList: [],
        columnList,
        showAll: false,
        query: {
          showMark: undefined,
          keyWord: undefined,
          creatorTime: undefined,
          startTime: undefined,
          endTime: undefined,
        },
        treeProps: {
          children: 'children',
          label: 'name',
          value: 'id'
        },
        list: [],
        listLoading: true,
        total: 0,
        listQuery: {
          superQueryJson: '',
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "",
        },
        flowVisible: false,
        exportBoxVisible: false,
        treeData: [{
          name: '商品分类',
          id:'-1',
          children: []
        }],
        treeActiveId: '',
        filterText: '',
        goodsTypeIdProps: {
          "label": "fullName",
          "value": "id"
        },
        goodsunitidOptions: [],
        goodsunitidProps: {
          "label": "fullName",
          "value": "id"
        },
        showmarkOptions: [{
          "fullName": "上架",
          "id": 1
        }, {
          "fullName": "下架",
          "id": 0
        }],
        showmarkProps: {
          "label": "fullName",
          "value": "id"
        },
      }
    },
    watch: {
      filterText(val) {
        this.$refs.treeBox.filter(val)
      }
    },
    computed: {
      menuId() {
        return this.$route.meta.modelId || ''
      }
    },
    created() {
      this.getColumnList(),
        this.getTreeView();
    },
    methods: {
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      getColumnList() {
        // 没有开启权限
        this.columnOptions = this.transformColumnList(this.columnList)
      },
      transformColumnList(columnList) {
        let list = []
        for (let i = 0; i < columnList.length; i++) {
          const e = columnList[i];
          if (!e.prop.includes('-')) {
            list.push(e)
          } else {
            let prop = e.prop.split('-')[0]
            let label = e.label.split('-')[0]
            let vModel = e.prop.split('-')[1]
            let newItem = {
              align: "center",
              jnpfKey: "table",
              prop,
              label,
              children: []
            }
            e.vModel = vModel
            if (!this.expandObj.hasOwnProperty(`${prop}Expand`)) this.$set(this.expandObj, `${prop}Expand`, false)
            if (!list.some(o => o.prop === prop)) list.push(newItem)
            for (let i = 0; i < list.length; i++) {
              if (list[i].prop === prop) {
                list[i].children.push(e)
                break
              }
            }
          }
        }
        this.getMergeList(list)
        this.getExportList(list)
        return list
      },
      arraySpanMethod({
        column
      }) {
        for (let i = 0; i < this.mergeList.length; i++) {
          if (column.property == this.mergeList[i].prop) {
            return [this.mergeList[i].rowspan, this.mergeList[i].colspan]
          }
        }
      },
      getMergeList(list) {
        let newList = JSON.parse(JSON.stringify(list))
        newList.forEach(item => {
          if (item.children && item.children.length) {
            let child = {
              prop: item.prop + '-child-first'
            }
            item.children.unshift(child)
          }
        })
        newList.forEach(item => {
          if (item.children && item.children.length > 0) {
            item.children.forEach((child, index) => {
              if (index == 0) {
                this.mergeList.push({
                  prop: child.prop,
                  rowspan: 1,
                  colspan: item.children.length
                })
              } else {
                this.mergeList.push({
                  prop: child.prop,
                  rowspan: 0,
                  colspan: 0
                })
              }
            })
          } else {
            this.mergeList.push({
              prop: item.prop,
              rowspan: 1,
              colspan: 1
            })
          }
        })
      },
      getExportList(list) {
        let exportList = []
        for (let i = 0; i < list.length; i++) {
          if (list[i].jnpfKey === 'table') {
            for (let j = 0; j < list[i].children.length; j++) {
              exportList.push(list[i].children[j])
            }
          } else {
            exportList.push(list[i])
          }
        }
        this.exportList = exportList
      },
      sortChange({
        column,
        prop,
        order
      }) {
        this.listQuery.sort = order == 'ascending' ? 'asc' : 'desc'
        this.listQuery.sidx = !order ? '' : prop
        this.initData()
      },
      getTreeView() {
        getDataInterfaceRes().then(res => {
          if(res.code == 200){
            this.treeData[0].children = JSON.parse(JSON.stringify(res.data.list))
          }
          this.initData()
        })
      },
      handleNodeClick(data) {
        this.treeActiveId = data.id
        for (let
            key in this.query) {
          this.query[key] = undefined
        }
        this.query.goodsTypeId = data.id
        this.listQuery = {
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "",
        }
        this.initData()
      },
      initData() {
        this.listLoading = true;
        if(this.query.creatorTime && this.query.creatorTime.length == 2){
          this.query.startTime = this.jnpf.toDate(new Date(this.query.creatorTime[0]).getTime(), 'yyyy-MM-dd HH:mm:ss')
          this.query.endTime = this.jnpf.toDate(new Date(this.query.creatorTime[1]).getTime(), 'yyyy-MM-dd HH:mm:ss')
        }
        let _query = {
          ...this.listQuery,
          ...this.query,
          keyword: this.keyword,
          dataType: 0,
          menuId: this.menuId,
          goodsTypeId: this.treeActiveId && this.treeActiveId != '-1' ? this.treeActiveId : undefined
        };
        request({
          url: `/api/zgyf/Goods/getList`,
          method: 'post',
          data: _query
        }).then(res => {
          res.data.list.forEach(item=>{
            if(JSON.parse(item.image)[0]){
              item.url = JSON.parse(item.image)[0].url
            }
          })
          this.list = JSON.parse(JSON.stringify(res.data.list))
          this.total = res.data.pagination.total
          this.listLoading = false
        }).catch(()=>{
          this.listLoading = false
        })
      },
      handleDel(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          type: 'warning'
        }).then(() => {
          request({
            url: `/api/zgyf/Goods/${id}`,
            method: 'DELETE'
          }).then(res => {
            this.$message({
              type: 'success',
              message: res.msg,
              onClose: () => {
                this.initData()
              }
            });
          })
        }).catch(() => {});
      },
      addOrUpdateHandle(id, flowState) {
        let data = {
          id: id || '',
          enCode: 'goodsList',
          flowId: '367553564446295301',
          formType: 1,
          opType: flowState ? 0 : '-1',
          status: flowState
        }
        this.flowVisible = true
        this.$nextTick(() => {
          this.$refs.FlowBox.init(data)
        })
      },
      showHandle(id){
        request({
          url: `/api/zgyf/Goods/show/${id}`,
          method: 'put'
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.initData()
            }
          })
        })
      },
      offHandle(id){
        request({
          url: `/api/zgyf/Goods/off/${id}`,
          method: 'put'
        }).then((res) => {
          this.$message({
            message: res.msg,
            type: 'success',
            duration: 1000,
            onClose: () => {
              this.initData()
            }
          })
        })
      },
      exportData() {
        this.exportBoxVisible = true
        this.$nextTick(() => {
          this.$refs.ExportBox.init(this.exportList)
        })
      },
      download(data) {
        let query = {
          ...data,
          ...this.listQuery,
          ...this.query,
          menuId: this.menuId
        }
        request({
          url: `/api/zgyf/Goods/Actions/Export`,
          method: 'post',
          data: query
        }).then(res => {
          if (!res.data.url) return
          this.jnpf.downloadFile(res.data.url)
          this.$refs.ExportBox.visible = false
          this.exportBoxVisible = false
        })
      },
      search(init) {
        this.listQuery.currentPage = 1
        this.listQuery.pageSize = 20
        this.listQuery.sort = "desc"
        this.listQuery.sidx = ""
        if(init){
          this.treeActiveId = '-1'
          this.getTreeView()
        }else{
          this.initData()
        }
      },
      colseFlow(isrRefresh) {
        this.flowVisible = false
        if (isrRefresh) this.reset()
      },
      reset(init) {
        for (let key in this.query) {
          this.query[key] = undefined
        }
        this.search(init)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .tree-search{
    margin: 10px 15px;
  }
</style>
